<?php
/**
 * Created by Mr.hu.
 * Date: 2017/3/2
 * Time: 11:25
 * Description:'优惠券模型'
 */
namespace bc\model\coupons;
use bc\ar\MActiveRecord;
use bc\model\ProductModel;

class CouponsModel extends MActiveRecord{
    public $create_data;//收集数据
    public $create_error;//数据创建错误信息
    public $autoId='coupons_id';

    public static $bc_coupons_coupons_type=[
        '1'=>'红包',
        '2'=>'满减'
    ];

    public static function tableName()
    {
        return "{{%coupons}}";
    }


    /**
     * Created by Mr.hu.
     * Description:获取产品列表
     */
    public  function getProductList()
    {
        return  (new ProductModel())->getList('product_id >= 0');
    }

    /**
     * Created by Mr.hu.
     * Description:获取产品组列表
     */
    public static function getProductGroupList()
    {
        return array();
    }


    /**
     * Created by Mr.hu.
     * @param $type
     * @param $params
     * Description:验证创建数据
     */
    public function _self_validate($type,$params)
    {
        $save_data=array();//保存用户填写的信息
        switch ($type){
            case 'add':
            case 'edit':
                //优惠券名称
                if($params['coupons_name']){
                    $save_data['coupons_name']=$params['coupons_name'];
                }else{
                    $this->create_error='优惠券名称必须填写';
                    break;
                }

                //类型
                if($params['coupons_type']){
                    $save_data['coupons_type']=$params['coupons_type'];
                }else{
                    $this->create_error='优惠券类型必须选择';
                    break;
                }


                //满金额
                if($params['coupons_type']==2){
                    if(is_numeric($params['coupons_full_money'])&&intval($params['coupons_full_money'])>0){
                        $save_data['coupons_full_money']=$params['coupons_full_money'];
                    }else{
                        $this->create_error='满金额必须是大于0的数字';
                        break;
                    }
                }


                //优惠券的金额
                if(is_numeric($params['coupons_money'])&&intval($params['coupons_money'])>0){
                    $save_data['coupons_money']=$params['coupons_money'];
                }else{
                    $this->create_error='优惠券金额必须是大于0的数字';
                    break;
                }


                //发放方式
                if(in_array($params['coupons_release_type'],array('1','2','3'))){
                    $save_data['coupons_release_type']=$params['coupons_release_type'];
                }else{
                    $this->create_error='选择正确的发放方式';
                    break;
                }

                //领取次数
                if(preg_match("/^\d+$/",$params['coupons_limit_number'])){
                    $save_data['coupons_limit_number']=intval($params['coupons_limit_number']);
                }else{
                    $this->create_error='领取次数是大于0的整数';
                    break;
                }

                //使用范围
                if(in_array($params['coupons_use_target'],array('1','2','3'))){
                    $save_data['coupons_use_target']=$params['coupons_use_target'];
                }else{
                    $this->create_error='请选择正确的使用范围';
                    break;
                }

                //选择正确使用产品
                if($params['coupons_use_target']==1&&$params['product_id']){
                    $save_data['product_id']=$params['product_id'];
                }elseif ($params['coupons_use_target']==2&&$params['product_group_id']){
                    $save_data['product_group_id']=$params['product_group_id'];
                }elseif($params['coupons_use_target']==3){
                    $save_data['product_group_id']='';
                    $save_data['product_id']='';
                }

                //发放的有效时间
                if($params['release_start_time']&&$params['release_end_time']){
                    if(strtotime($params['release_end_time'])>strtotime($params['release_start_time'])){
                        $save_data['release_start_time']=$params['release_start_time'];
                        $save_data['release_end_time']=$params['release_end_time'];
                    }else{
                        $this->create_error='结束时间必须大于开始时间';
                        break;
                    }
                }else{
                    $this->create_error='选取有效的发放时间';
                    break;
                }

                //使用的有效时间
                if($params['use_start_time']&&$params['use_end_time']){
                    if(strtotime($params['use_end_time']) > strtotime($params['use_start_time'])){
                        $save_data['use_end_time']=$params['use_end_time'];
                        $save_data['use_start_time']=$params['use_start_time'];
                    }else{
                        $this->create_error='结束时间必须大于开始时间';
                        break;
                    }
                }else{
                    $this->create_error='选取有效的使用时间';
                    break;
                }
                //添加时间
                $save_data['create_time']=date('Y-m-d H:i:s');

                break;
        }

        //时间
        if($type==='edit'){
            $save_data['update_time']=date('Y-m-d H:i:s');
        }elseif($type==='add'){
            $save_data['create_time']=date('Y-m-d H:i:s');
        }

        $this->create_data=$save_data;
        return $this->create_error?false:true;
    }

    
    /**
     * 
     * @param string $params
     */
	public function getFrontendList($params, $groupBy)
	{
		$columns = self::getTableSchema()->name . '.*, count(' . CouponsUserModel::getTableSchema()->name . '.coupons_id) AS total';
		$ar = $this->find ()->select($columns)
				->leftJoin(CouponsUserModel::getTableSchema()->name,  self::getTableSchema()->name . '.coupons_id = ' . CouponsUserModel::getTableSchema()->name . '.coupons_id')
				->where($params)
				->groupBy($groupBy);
		if($this->sort)
			$ar->orderBy($this->sort);
			
// 		echo $ar->createCommand()->getRawSql();	
		return $ar->asArray()->all();
	}
    
    
    
    /**
     * 
     */
    public function getListTotal($params, $groupBy)
    {
    	if(!empty($params))
			return $this->find()->leftJoin(CouponsUserModel::getTableSchema()->name, CouponsUserModel::getTableSchema()->name . '.coupons_id = ' . self::getTableSchema()->name . '.coupons_id')->where($params)->groupBy($groupBy)->count();
		else
			return 0;
    }
    
    
    /**
     * 获取可用的优惠券
     * @param string|array $params
     */
    public function getAvailableList($params)
    {
    	$ar = $this->find ()->select($this->columns)
    			->leftJoin(CouponsUserModel::getTableSchema()->name,  self::getTableSchema()->name . '.coupons_id = ' . CouponsUserModel::getTableSchema()->name . '.coupons_id')
    			->where($params);
    	if($this->sort)
    		$ar->orderBy($this->sort);
    	
    	return $ar->asArray()->all();
    }

    /*
     * 获取用户优惠券的使用记录
     * $userid:用户ID'0'=>'未使用','1'=>'已使用','2'=>'赠送中','3'=>'已赠送'
     * $productid:产品ID，默认为空，表示获取所有商品
     * $status:状态，默认为空，表示获取所有状态
     * $coupons_type:优惠券类型，默认表示获取所有类型
     * */
    public function getCouponInfo($userid,$status=null,$productid=null,$coupons_type=null)
    {
        $where=['bc_coupons_user.user_id'=>$userid];
        empty($productid) or $where['bc_coupons.product_id']=$productid;
        ($status===null) or $where['bc_coupons_user.status']=($status == 4)? array(0,1,2,3):explode(',',$status);
        empty($coupons_type) or $where['bc_coupons.coupons_type']=$coupons_type;

        $ar = $this->find ()->select($this->columns)
            ->leftJoin('bc_coupons_user','bc_coupons_user.coupons_id = bc_coupons.coupons_id')
            ->groupBy('bc_coupons_user.coupons_id,coupons_status'.(($status == 4 || $status == 0)?'':',bc_coupons_user.status'))
            ->where($where);

        ($status===null) or $ar->having('coupons_status in ('.$status.')');

//        echo $ar->createCommand()->getRawSql();
        if($this->sort)
            $ar->orderBy($this->sort);
        $tempData1 =  $ar->asArray()->all();

        $tempData2=($status=='1,2,3') ? $this->getCouponTotalFromUser($userid,$productid,$coupons_type) :array();
//        var_dump($tempData2);
        return array_merge($tempData1,$tempData2);
    }

    /*
     * 获取用户优惠券的各状态总数
     * $userid:用户ID
     * 返回值是以状态为key值
     * */
    public function getCouponTotalFromStatus($userid,$date,$productid=null,$coupons_type=null)
    {
        $where=['bc_coupons_user.user_id'=>$userid];
        $ar = $this->find ()->select('count(bc_coupons_user.status) as total,CASE
        					WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=0 THEN 4
							WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=1 THEN 1
							WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=2 THEN 4
							WHEN `bc_coupons`.`use_end_time` < \''.$date.'\' and `bc_coupons_user`.`status`=3 THEN 4
        					WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=0 THEN 0
							WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=1 THEN 1
							WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=2 THEN 2
							WHEN `bc_coupons`.`use_end_time` >= \''.$date.'\' and `bc_coupons_user`.`status`=3 THEN 3
   						END as coupons_status')
            ->leftJoin('bc_coupons_user','bc_coupons_user.coupons_id = bc_coupons.coupons_id')
            ->groupBy('coupons_status')
            ->where($where);
        if($this->sort)
            $ar->orderBy($this->sort);
//        echo $ar->createCommand()->getRawSql();
        $list = $ar->asArray()->all();



        $retData=array();
        foreach($list as $k=>$v) {
            $retData[$v['coupons_status']]=$v['total'];
        }
        $tempData=$this->getCouponTotalFromUser($userid,$productid,$coupons_type);
        $total=0;
        foreach($tempData as $k => $v)
        {
            $total+=$v['total'];
        }
        $retData[3]+=$total;
        return $retData;
    }

    //获取用户已赠送的优惠券
    public function getCouponTotalFromUser($userid)
    {
        $where=['bc_coupons_user.from_user_id'=>$userid];
        empty($productid) or $where['bc_coupons.product_id']=$productid;
        empty($coupons_type) or $where['bc_coupons.coupons_type']=$coupons_type;

        $ar = $this->find ()->select($this->columns)
            ->leftJoin('bc_coupons_user','bc_coupons_user.coupons_id = bc_coupons.coupons_id')
            ->groupBy('bc_coupons_user.coupons_id')
            ->where($where);
//        echo $ar->createCommand()->getRawSql();
        if($this->sort)
            $ar->orderBy($this->sort);
        $list = $ar->asArray()->all();

        foreach($list as $k=>$v) {
            $list[$k]['coupons_status']=3;
        }

        return $list;
    }
}